package io.dcloud.uniplugin.bc;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;


import java.util.HashMap;
import java.util.Map;

import io.dcloud.uniplugin.TestModule;
import io.flutter.embedding.android.FlutterFragment;
import io.flutter.embedding.android.RenderMode;
import tech.brainco.trainsdk.BcTrainPlugin;
import tech.brainco.trainsdk.api.BcTrainListener;
import tech.brainco.trainsdk.model.BcOnIntroFinishAction;
import tech.brainco.trainsdk.model.BcOnLongTimeNotPlayAction;
import tech.brainco.trainsdk.model.BcOnTrainLoadErrorAction;
import tech.brainco.trainsdk.model.BcTrainFinishData;
import tech.brainco.trainsdk.model.BcTrainState;
import tech.brainco.trainsdk.model.DeviceNotContactException;
import tech.brainco.trainsdk.utils.BcLogger;
import uni.dcloud.io.uniplugin_module.R;

/**
 * 训练页
 */
public class TrainActivity extends FragmentActivity {
    private static final String TAG_FLUTTER_FRAGMENT = "bc_train_fragment";

    private FlutterFragment flutterFragment;

    private final BcTrainPlugin trainPlugin = BcTrainPlugin.getInstance();

    BcTrainListener trainListener = null;

    int trainState = -1;
    Button actionButton = null;
    Button reloadButton = null;
    ImageButton backButton = null;

    AlertDialog onLoadErrorDialog = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.e( "trainOnCreate: ",TrainActivity.this.toString() );
        setContentView(R.layout.train_activity_layout);


        // 隐藏状态栏和导航栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN |  // 隐藏状态栏
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |  // 隐藏导航栏
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);  // 保持全屏模式

        FragmentManager fragmentManager = getSupportFragmentManager();
        flutterFragment = (FlutterFragment) fragmentManager
                .findFragmentByTag(TAG_FLUTTER_FRAGMENT);

        if (flutterFragment == null) {
            // 使用缓存的引擎
            flutterFragment = FlutterFragment
                    .withCachedEngine(BcTrainPlugin.TRAIN_ENGINE_ID)
                    .renderMode(RenderMode.texture)
                    .build();

            fragmentManager
                    .beginTransaction()
                    .add(
                            R.id.fragment_container,
                            flutterFragment,
                            TAG_FLUTTER_FRAGMENT
                    )
                    .commit();
        }

        actionButton = findViewById(R.id.btn_train_action);
        actionButton.setOnClickListener(v -> {
            if (trainState == BcTrainState.STARTED || trainState == BcTrainState.RESUMED) {
                trainPlugin.pause();
            } else if (trainState == BcTrainState.PAUSED) {
                trainPlugin.resume();
            }
        });
        actionButton.setVisibility(View.GONE);  // 隐藏视图，并且不占用空间


        reloadButton = findViewById(R.id.btn_train_reload);
        reloadButton.setOnClickListener(v -> {
            //清本地游戏包，然后重新加载在线游戏
            trainPlugin.clearCacheAndReload();
        });
        reloadButton.setVisibility(View.GONE);  // 隐藏视图，并且不占用空间

        backButton = findViewById(R.id.imgbtn_left_arrow);
        backButton.setOnClickListener(v -> {
            onBackPressed();
        });
        //返回按钮刚开始不可见
        backButton.setVisibility(View.GONE);



        Intent intent = getIntent();
        if (intent != null) {
            int courseId = intent.getIntExtra("courseId", 0);
            int stage = intent.getIntExtra("stage", 0);
            boolean withIntro = intent.getBooleanExtra("withIntro", false);
            int duration = intent.getIntExtra("duration", -1);
            int bestScore = intent.getIntExtra("bestScore", 0);//部分游戏支持
            if (courseId != 0 && stage != 0) {
                //开始训练
                try {
                    trainPlugin.start(courseId, stage, withIntro, duration, bestScore); //duration 大于0则按此时长，否则则按关卡设定的时长，
                } catch (DeviceNotContactException e) {
                    Toast.makeText(this, "头环未佩戴好", Toast.LENGTH_SHORT).show();
                }
            }
        }
        trainListener = new BcTrainListener() {

            @Override
            public void onStateChange(int state) {
                //训练状态回调
                //BcTrainState.IDLE = 0;  初始状态
                //BcTrainState.STARTED = 1;  已开始
                //BcTrainState.PAUSED = 2;  已暂停
                //BcTrainState.RESUMED = 3;  已暂停
                //BcTrainState.DONE = 4;  已暂停
                //BcTrainState.RELEASED = 5;  已销毁
                BcLogger.d("onTrainStateChange", "state: " + state);
                trainState = state;
                if (trainState == BcTrainState.STARTED || trainState == BcTrainState.RESUMED) {
                    actionButton.setText("暂停");
                } else if (trainState == BcTrainState.PAUSED) {
                    actionButton.setText("继续");
                }
                //训练开始后，返回按钮可见
                if(trainState == BcTrainState.STARTED){
                    backButton.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFinish(BcTrainFinishData result) {
                Map map = new HashMap<>();
                map.put("result", result);
                Log.e("onGameResult: ", result.toString());
                TestModule.myUniSDKInstance.fireGlobalEventCallback("onGameResult", map);

//                moveTaskToBack(true);
//                Intent intent = new Intent();
//                intent.setClassName("com.android.UniPlugin", "io.dcloud.PandoraEntry");
//                intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//                startActivity(intent);
                //训练结束回调
                BcLogger.d("onTrainFinish", result.toString());
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAndRemoveTask();
                }else {
                    finishAffinity();
                }

//                AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
//                builder.setCancelable(false);
//                builder.setTitle("训练结束");
//                builder.setMessage("训练结果：" + result);
//                builder.setPositiveButton("再来一次", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int id) {
//                        flutterFragment.onBackPressed();
//                        Intent intent = getIntent();
//                        if (intent != null) {
//                            int courseId = intent.getIntExtra("courseId", 0);
//                            int stage = intent.getIntExtra("stage", 0);
//                            boolean withIntro = intent.getBooleanExtra("withIntro", false);
//                            int duration = intent.getIntExtra("duration", -1);
//                            int bestScore = intent.getIntExtra("bestScore", 0);//部分游戏支持
//                            if (courseId != 0 && stage != 0) {
//                                //开始训练
//                                try {
//                                    trainPlugin.start(courseId, stage, withIntro, duration, bestScore); //duration 大于0则按此时长，否则则按关卡设定的时长，
//                                } catch (DeviceNotContactException e) {
//                                    Toast.makeText(TrainActivity.this, "头环未佩戴好", Toast.LENGTH_SHORT).show();
//                                }
//                            }
//                        }
//                    }
//                });
//                builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int id) {
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                            finishAndRemoveTask();
//                        }else {
//                            finishAffinity();
//                        }
//                    }
//                });
//                AlertDialog dialog = builder.create();
//                dialog.show();
            }

            @Override
            public void onIntroSkipClicked() {
                BcLogger.d("onIntroSkipClicked", "");
            }

            @Override
            public void onIntroFinish(BcOnIntroFinishAction nextAction) {
                //新手引导结束回调
                BcLogger.d("onTrainIntroFinish", "");
                AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
                builder.setCancelable(false);
                builder.setTitle("引导结束");
                builder.setMessage("新手教学已完成，是否马上开始训练？");
                builder.setPositiveButton("开始训练", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        nextAction.startTrain();
                    }
                });
                builder.setNegativeButton("再看一次", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        nextAction.replayIntro();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onLongTimeNotPlay(BcOnLongTimeNotPlayAction nextAction) {
                //长时间未进行操作回调
                BcLogger.d("onLongTimeNotPlay", "");
                AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
                builder.setCancelable(false);
                builder.setTitle("提醒");
                builder.setMessage("检测到你长时间未进行操作。这样会影响训练效果哦，快活跃起来吧！");
                builder.setPositiveButton("重新训练", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        nextAction.restart();
                    }
                });
                builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        onBackPressed();
                    }
                });
//                builder.setNegativeButton("继续", new DialogInterface.OnClickListener() {
//                    public void onClick(DialogInterface dialog, int id) {
//                        trainPlugin.resume();
//                    }
//                });
                AlertDialog dialog = builder.create();
                dialog.show();
            }

            @Override
            public void onLoadError(BcOnTrainLoadErrorAction nextAction) {
                //加载失败回调
                BcLogger.d("onLoadError", "");
                if (onLoadErrorDialog != null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
                builder.setCancelable(false);
                builder.setTitle("加载失败");
                builder.setMessage("网络异常,请检查网络后再重试");
                builder.setPositiveButton("重试", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        nextAction.restart();
                    }
                });
                builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        onBackPressed();
                    }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        onLoadErrorDialog = null;
                    }
                });
                onLoadErrorDialog = dialog;
            }
        };
        trainPlugin.addTrainListener(trainListener);

    }

    @Override
    public void onBackPressed() {

        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(TrainActivity.this);
        builder.setCancelable(true);
        builder.setTitle("退出训练");
        builder.setMessage("现在退出，该部分的本次训练数据不会被保留，确认退出训练吗?");

        builder.setPositiveButton("继续训练", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                // 点击"继续训练"时，不做任何操作，只关闭对话框
                dialog.dismiss();
            }
        });

        builder.setNegativeButton("退出训练", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                // 用户点击"退出训练"，处理退出逻辑
//                trainPlugin.removeTrainListener(trainListener);
//                trainPlugin.quitCourse();


                Map map = new HashMap<>();
                map.put("result", "");
                Log.e("trainAct", "onBackPressed: Q");
                TestModule.myUniSDKInstance.fireGlobalEventCallback("onGameReturn", map);
                // 退出当前 Activity
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAndRemoveTask();
                }else {
                    finishAffinity();
                }
                dialog.dismiss();
//                finish(); // 结束当前Activity，返回前一个 Activity


            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();


//        flutterFragment.onBackPressed();
//        super.onBackPressed();
    }

    public void onDestroy() {
        Log.e( "trainOnDestroy: ",TrainActivity.this.toString() );
        trainPlugin.removeTrainListener(trainListener);
        trainPlugin.quitCourse();
        super.onDestroy();
//        EventBus.getDefault().unregister(this);
    }

    protected void onPause() {
        super.onPause();
        Log.e("TrainActivity", "onPause: ");

        if (trainState == BcTrainState.STARTED || trainState == BcTrainState.RESUMED) {
            Log.e("TrainActivity", "onPause: 11");

            trainPlugin.pause(); // 游戏切换到后台时暂停
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("TrainActivity", "onResume: " + trainState);

        trainPlugin.resume(); // 游戏从后台切换到前台时继续

//        if (trainState == BcTrainState.PAUSED) {
//            Log.e("TrainActivity","onResume: 11" );
//
//            trainPlugin.resume(); // 游戏从后台切换到前台时继续
//        }
    }
}
